<template>
  <div v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef">
      <FormItem name="mobile" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.mobile"
          :placeholder="t('sys.login.mobile')"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="clarity-mobile-phone-solid" />
          </template>
        </Input>
      </FormItem>
      <FormItem name="smsCode" class="enter-x">
        <CountdownInput
          size="large"
          v-model:value="formData.smsCode"
          :placeholder="t('sys.login.smsCode')"
          :sendCodeApi="handleSmsVerifyCode"
          icon="tabler:device-mobile-message"
          class="fix-auto-fill"
        >
          <template #prefix>
            <Icon icon="tabler:device-mobile-message" />
          </template>
        </CountdownInput>
      </FormItem>

      <Button
        type="primary"
        class="enter-x"
        size="large"
        block
        @click="handleConfirmPhone"
        :loading="loading"
      >
        {{ t('sys.login.confirmTitle') }}
      </Button>
      <Button size="large" block class="mt-4 enter-x" @click="handleBack">
        {{ t('sys.login.backSignIn') }}
      </Button>
    </Form>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, toRaw, unref, computed, watchEffect, h } from 'vue';

  import LoginFormTitle from './LoginFormTitle.vue';
  import { Form, Input, Button } from 'ant-design-vue';
  import { CountdownInput } from '@/components/CountDown';
  import Icon from '@/components/Icon/Icon.vue';
  import { useDesign } from '@/hooks/web/useDesign';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useLoginState, useFormRules, useFormValid, LoginStateEnum } from './useLogin';

  import { useMessage } from '@/hooks/web/useMessage';
  import { isMobileNumber } from '@/enums/regexEnum';
  import { sendSmsVerifyCode } from '@/api/sms';
  import { confirmPhone } from '@/api/identity';

  const FormItem = Form.Item;

  const { t } = useI18n();
  const { prefixCls } = useDesign('login');
  const { handleBackLogin, handleAjaxResult, getLoginState, setUserAccount, getUserAccountState } =
    useLoginState();
  const { createErrorModal } = useMessage();

  const formRef = ref();
  const loading = ref(false);

  const formData = reactive({
    mobile: '',
    smsCode: '',
    smsCodeId: '',
  });

  const { getFormRules } = useFormRules(formData);
  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.CONFIRM_PHONE);

  watchEffect(async () => {
    const userAccountState = computed(() => unref(getUserAccountState));
    formData.mobile = userAccountState.value;
  });

  /** 处理激活手机 */
  async function handleConfirmPhone() {
    loading.value = true;
    try {
      const data = await validForm();
      if (!data) return;
      //console.log(data);
      setUserAccount(formData.mobile);
      const dto = toRaw({
        PhoneNumber: formData.mobile,
        SmsCode: formData.smsCode,
        SmsCodeId: formData.smsCodeId,
        mode: 'none', //不要默认的错误提示
      });
      const ajaxResult = await confirmPhone(dto);
      if (ajaxResult.Succeeded) {
        clearFormData();
        handleAjaxResult(ajaxResult, LoginStateEnum.CONFIRM_RESULT);
      }
    } catch (error: any) {
      showErrorModal(t('sys.api.errorTip'), error?.message || t('sys.api.networkExceptionMsg'));
    } finally {
      loading.value = false;
    }
  }

  /** 处理返回 */
  async function handleBack() {
    clearFormData();
    handleBackLogin();
  }

  /** 处理短信验证码 */
  async function handleSmsVerifyCode() {
    if (formData.mobile === undefined || formData.mobile === null || formData.mobile === '') {
      showErrorModal(t('sys.api.errorTip'), t('sys.login.mobilePlaceholder'));
      return false;
    }
    if (!isMobileNumber(formData.mobile)) {
      showErrorModal(t('sys.api.errorTip'), t('sys.login.mobileFormatError'));
      return false;
    }
    try {
      const dto = toRaw({ PhoneNumber: formData.mobile, mode: 'none' });
      const ajaxResult = await sendSmsVerifyCode(dto);
      if (!ajaxResult.Succeeded) {
        showErrorModal(t('sys.api.errorTip'), ajaxResult.Content);
        return false;
      }
      formData.smsCodeId = ajaxResult.Data as string;
      return true;
    } catch (error: any) {
      return false;
    }
  }

  function showErrorModal(title: string, content: string) {
    createErrorModal({
      zIndex: 999999999,
      title: () => h('span', title),
      content: () => h('span', content),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    });
  }

  /** 清除表单数据 */
  function clearFormData() {
    formData.smsCode = '';
    formData.smsCodeId = '';
  }
</script>
